<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />

      <el-table-column label="宗地序号" min-width="70">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.id`"  class="mb-0px!">
            <el-input v-model="row.id" placeholder="请输入宗地序号" disabled/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="宗地编号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.landNo`" :rules="formRules.landNo" class="mb-0px!">
            <el-input v-model="row.landNo" placeholder="请输入宗地编号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="土地证号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landCertificate`"
            :rules="formRules.landCertificate"
            class="mb-0px!"
          >
            <el-input v-model="row.landCertificate" placeholder="请输入土地证号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="宗地坐落" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landLocation`"
            :rules="formRules.landLocation"
            class="mb-0px!"
          >
            <el-input v-model="row.landLocation" placeholder="请输入宗地坐落" />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属区县" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landDistrict`"
            :rules="formRules.landDistrict"
            class="mb-0px!"
          >
            <el-input v-model="row.landDistrict" placeholder="请输入所属区县" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="所属乡镇" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landTownship`"
            :rules="formRules.landTownship"
            class="mb-0px!"
          >
            <el-input v-model="row.landTownship" placeholder="请输入所属乡镇" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="所属村" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landVillage`"
            :rules="formRules.landVillage"
            class="mb-0px!"
          >
            <el-input v-model="row.landVillage" placeholder="请输入所属村" />
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="面积" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.landArea`" :rules="formRules.landArea" class="mb-0px!">
            <el-input v-model="row.landArea" placeholder="请输入面积" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="征收标准（元/平方米*年）" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.levyStandards`"
            :rules="formRules.levyStandards"
            class="mb-0px!"
          >
            <el-input v-model="row.levyStandards" placeholder="请输入征收标准（元/平方米*年）" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="权利性质" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.landQlxz`" :rules="formRules.landQlxz" class="mb-0px!">
            <el-input v-model="row.landQlxz" placeholder="请输入权利性质" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="批准用途" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landApprovedUse`"
            :rules="formRules.landApprovedUse"
            class="mb-0px!"
          >
            <el-input v-model="row.landApprovedUse" placeholder="请输入批准用途" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="实际用途" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landActualUse`"
            :rules="formRules.landActualUse"
            class="mb-0px!"
          >
            <el-input v-model="row.landActualUse" placeholder="请输入实际用途" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="土地级别" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.landLevel`" :rules="formRules.landLevel" class="mb-0px!">
            <el-input v-model="row.landLevel" placeholder="请输入土地级别" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="不动产单元号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landBdcdyh`"
            :rules="formRules.landBdcdyh"
            class="mb-0px!"
          >
            <el-input v-model="row.landBdcdyh" placeholder="请输入不动产单元号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="坐标" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landCoordinate`"
            :rules="formRules.landCoordinate"
            class="mb-0px!"
          >
            <el-upload
              v-model:file-list="row.coordinateFileList"
              action=""
              drag
              multiple
              :limit="1"
              :on-exceed="(file, fileList) => handleExceed(file, fileList, row, $index)"
              :auto-upload="false"
              accept=".shp,.zip"
              :on-change="(file, files) => openFile(file, files, row, $index)"
              :on-remove="(file, files) => handleRemove(file, files, row, $index)"
              :ref="(el) => setUploadRef(el, $index)"
            >
              <el-button type="success">选择或拖拽shp/zip文件</el-button>
            </el-upload>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="坐标" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.landCoordinate`"
            :rules="formRules.landCoordinate"
            class="mb-0px!"
          >
            <el-input
              v-model="row.landCoordinate"
              type="textarea"
              disabled
              placeholder="请输入坐标"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
            <el-input v-model="row.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.status`" :rules="formRules.status" class="mb-0px!">
            <el-select v-model="row.status" placeholder="请选择状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYS_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button type="danger" @click="handleDelete($index)" link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加宗地信息</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { RentApi } from '@/api/zszx/rent'
import { genFileId } from 'element-plus'
import { openShp, readShpZip } from '@/utils/gisTool'
const { proxy } = getCurrentInstance()

const props = defineProps<{
  landIds: undefined // 宗地序号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  landNo: [{ required: true, message: '宗地编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 存储所有上传组件的引用
const uploadRefs = ref([])
const setUploadRef = (el, index) => {
  uploadRefs.value[index] = el
}
/** 坐标文件个数超限操作 */
function handleExceed(exceedFiles, currentFiles, row, index) {
  console.log(exceedFiles, currentFiles, row, index)
  // proxy.$refs[`shpUpload${index}`].clearFiles()
  uploadRefs.value[index].clearFiles()
  row.landCoordinate = undefined
  const newFile = exceedFiles[0]
  newFile.uid = genFileId()
  proxy.$refs[`shpUpload${index}`].handleStart(newFile)
}
/** 上传坐标文件操作 */
async function openFile(file, files, row, index) {
  console.log('file', file, files, row, index)
  let extension = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase()
  if (extension == 'zip') {
    let coor = JSON.stringify(await readShpZip(file))
    row.landCoordinate = coor
  } else if (extension == 'shp') {
    let coor = JSON.stringify(await openShp(file))
    row.landCoordinate = coor
  }
}
/** 移除坐标操作 */
function handleRemove(file, uploadFiles, row, index) {
  row.landCoordinate = undefined
  uploadRefs.value[index].clearFiles()// proxy.$refs[`shpUpload${index}`].clearFiles()
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.landIds,
  async (val) => {
    // console.log(props.landIds, val)
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      formData.value = await RentApi.getLandListByLandIds(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    landNo: undefined,
    landCertificate: undefined,
    landLocation: undefined,
    landDistrict: undefined,
    landTownship: undefined,
    landVillage: undefined,
    landArea: undefined,
    levyStandards: undefined,
    landQlxz: undefined,
    landApprovedUse: undefined,
    landActualUse: undefined,
    landLevel: undefined,
    landBdcdyh: undefined,
    landCoordinate: undefined,
    remark: undefined,
    status: undefined
  }
  row.id = props.id
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })
</script>
